#!/bin/sh /etc/rc.common

START=97
STOP=14
SERVICE_WRITE_PID=1
SERVICE_DAEMONIZE=1
SERVICE_UID='nobody'

EXEC="/usr/bin/chinadns"
OPTIONS=""

config_cb() {
    [ "$1" = "chinadns" ] && {
    OPTIONS="$OPTIONS -c /etc/ipset/whitelist"
    }
}

append_args() {
	[ -n "$2" ] && OPTIONS="$OPTIONS $1$2"
}

trans_args() {
	case "$1" in
		'dnscpm'			) [ "$2" = '1' ] && OPTIONS="$OPTIONS -m";;
		'bidirectional'			) [ "$2" = '1' ] && OPTIONS="$OPTIONS -d";;
		'dns'				) append_args '-s' "$2";;
		'port'				) append_args '-p' "$2";;
		'delay'				) append_args '-y' "$2";;
	esac
}

option_cb() {
	trans_args "$1" "$2"
}

section_enabled() {
	local enabled
	config_get_bool enabled "$1" 'enabled' 0
	[ $enabled -eq 1 ]
}

start_instance() {
	local port
	config_get port "$1" 'port' 1053
	section_enabled "$1" && {
	service_start $EXEC $OPTIONS
	uci del dhcp.@dnsmasq[-1].server
	uci set dhcp.@dnsmasq[-1].noresolv=1
	uci add_list dhcp.@dnsmasq[-1].server=127.0.0.1#$port
	uci commit dhcp
	/etc/init.d/dnsmasq restart
	}
}

start()
{
	config_load "chinadns"
	config_foreach start_instance 'chinadns'
}

stop()
{
	service_stop $EXEC
        uci set dhcp.@dnsmasq[-1].noresolv=0
        uci del dhcp.@dnsmasq[-1].server
        uci commit dhcp
        /etc/init.d/dnsmasq restart
}
